//
//  AppDelegate.m
//  Contractor
//
//  Created by star j on 16/4/18.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "AppDelegate.h"
#import "MainTabBarViewController.h"
#import "CONST.h"
#import "LocationModel.h"
#import "MBProgressHUD.h"
#import "KMCGeigerCounter.h"
#import <CoreLocation/CoreLocation.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
//#import <AVFoundation/AVFoundation.h>

BMKMapManager* _mapManager ;

@interface AppDelegate ()<BMKLocationServiceDelegate>
{
    CLLocationManager *locationManager ;
    BMKLocationService *_locService ;
    NSInteger counter ;
}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //是否第一次启动程序
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        NSLog(@"first launch第一次程序启动");
        
        [self locationDefaults] ;
    }
    
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"aobptY415XmgTQu7RtgXGVySQekg0EI7" generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds] ;
    
    _loginVC = [[LoginViewController alloc] init] ;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_loginVC] ;
    
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"status_look_popview_normal_bg.png"] forBarMetrics:UIBarMetricsDefault];//导航栏颜色
    [[UINavigationBar appearance] setBackgroundColor:[UIColor blueColor]] ;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]] ;//导航栏图标颜色
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];//导航栏文字颜色

    //[KMCGeigerCounter sharedGeigerCounter].enabled = YES;
    self.window.rootViewController = nav;
    //使窗口显示到最前端
    [self.window makeKeyAndVisible] ;
    return YES;
}

- (void)monitorBatteryStateInBackground
{
    self.background = YES;
    [self startBackgroundTask];
}

- (void)startBackgroundTask
{
    NSLog(@"Restarting task");
    // Start the long-running task.
//    dispatch_async(dispatch_get_main_queue(), ^{
//        self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:self.expirationHandler];
//    }) ;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // When the job expires it still keeps running since we never exited it. Thus have the expiration handler
        // set a flag that the job expired and use that to exit the while loop and end the task.
        NSInteger count=0;
        locationManager.distanceFilter = kCLDistanceFilterNone;//任何运动均接受，任何运动将会触发定位更新
        locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;//定位精度
        while(self.background && !self.jobExpired)
        {
            NSLog(@"进入后台进程循环");
            [NSThread sleepForTimeInterval:1];
            count++;
            if(count>10)//每10s进行一次开启定位，刷新后台时间
            {
                count=0;
               // [locationManager startUpdatingLocation];
                [_locService startUserLocationService] ;
                NSLog(@"开始位置服务");
                [NSThread sleepForTimeInterval:1];
               // [locationManager stopUpdatingLocation];
                [_locService stopUserLocationService] ;
                NSLog(@"停止位置服务");
            }

        }
        self.jobExpired = NO ;
    });
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations//当用户位置改变时，系统会自动调用，这里必须写一点儿代码，否则后台时间刷新不管用
{
    NSLog(@"位置改变，必须做点儿事情才能刷新后台时间");
    CLLocation *loc = [locations lastObject];
    //NSTimeInterval backgroundTimeRemaining = [[UIApplication sharedApplication] backgroundTimeRemaining];
    //NSLog(@"Background Time Remaining = %.02f Seconds",backgroundTimeRemaining);
    // Lat/Lon
    float latitudeMe = loc.coordinate.latitude;
    float longitudeMe = loc.coordinate.longitude;
}

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"位置改变，必须做点儿事情才能刷新后台时间 didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    double latitude = userLocation.location.coordinate.latitude ;
    double longitude = userLocation.location.coordinate.longitude ;
    
    NSString *longitudeNum = [NSString stringWithFormat:@"%.6f",longitude] ;
    NSString *latitudeNum = [NSString stringWithFormat:@"%.6f",latitude] ;
    
    NSUserDefaults *Defaults = [NSUserDefaults standardUserDefaults] ;
    [Defaults setValue:latitudeNum forKey:@"latitude"] ;
    [Defaults setValue:longitudeNum forKey:@"longitude"] ;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void) endBackgroundTask{
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    AppDelegate *weakSelf = self;
    dispatch_async(mainQueue, ^(void) {
        AppDelegate *strongSelf = weakSelf;
        if (strongSelf != nil){
            [strongSelf.myTimer invalidate];// 停止定时器
            // 标记指定的后台任务完成
            [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
            // 销毁后台任务标识符
            strongSelf.bgTask = UIBackgroundTaskInvalid;
        }
    });
}

// 模拟的一个 Long-Running Task 方法
- (void) timerMethod:(NSTimer *)paramSender{
    // backgroundTimeRemaining 属性包含了程序留给的我们的时间
    NSTimeInterval backgroundTimeRemaining =[[UIApplication sharedApplication] backgroundTimeRemaining];
    if (backgroundTimeRemaining == DBL_MAX){
        NSLog(@"Background Time Remaining = Undetermined");
    } else {
        NSLog(@"Background Time Remaining = %.02f Seconds", backgroundTimeRemaining);
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    
    self.bgTask =[application beginBackgroundTaskWithExpirationHandler:^(void) {
        
        // 当应用程序留给后台的时间快要到结束时（应用程序留给后台执行的时间是有限的）， 这个Block块将被执行
        // 我们需要在次Block块中执行一些清理工作。
        // 如果清理工作失败了，那么将导致程序挂掉
        
        // 清理工作需要在主线程中用同步的方式来进行
        [self endBackgroundTask];
    }];
    
    // 模拟一个Long-Running Task
    self.myTimer =[NSTimer scheduledTimerWithTimeInterval:1.0f
                                                   target:self
                                                 selector:@selector(timerMethod:)     userInfo:nil
                                                  repeats:YES];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self endBackgroundTask] ;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - 加载地域数据保存（只在第一次启动app时运行）


- (void)locationDefaults
{
    NSString *decodeStr = [CodeWithDES decodeWithStr:locationStr] ;
   
    NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
    id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
    //获取字典中的值
    if ([result isKindOfClass:[NSDictionary class]])
    {
        NSDictionary *dic = result ;
        // NSLog(@"dic:%@",dic) ;
        if (([dic[@"status"] integerValue] == 1) && ![dic[@"content"] isKindOfClass:[NSNull class]])
        {
            NSMutableArray *allArray = [NSMutableArray array] ;
            NSArray *content = dic[@"content"] ;
            for (NSDictionary *dic in content) {
                LocationModel *model = [[LocationModel alloc] init] ;
                [model setValuesForKeysWithDictionary:dic] ;
                [allArray addObject:model] ;
            }
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:allArray];
            // NSArray *array = [NSArray arrayWithArray:allArray] ;
            NSUserDefaults *uidDefaults = [NSUserDefaults standardUserDefaults] ;
            [uidDefaults setValue:data forKey:@"LocationArray"] ;
            
            NSData *data1 = [NSData dataWithData:[uidDefaults valueForKey:@"LocationArray"]] ;
            NSArray *array =  [NSKeyedUnarchiver unarchiveObjectWithData:data1] ;
            NSLog(@"array:%lu",(unsigned long)array.count) ;
        }
        
    }
}

@end
